package com.returnsoft.softphone.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;

import com.returnsoft.security.dto.PermissionDto;
import com.returnsoft.security.dto.UserDto;
import com.returnsoft.security.exception.SecurityExcepcion;
import com.returnsoft.security.service.UserInterface;
import com.returnsoft.softphone.dto.AgentDto;
import com.returnsoft.softphone.dto.SupervisorDto;
import com.returnsoft.softphone.exception.CCenterExcepcion;
import com.returnsoft.softphone.service.AgentInterface;
import com.returnsoft.softphone.service.SupervisorInterface;
import com.returnsoft.util.Util;

@ManagedBean
@RequestScoped
public class LoginController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;

	private final String PERMISSION_CCENTER_AGENT = "ccenter_agent";
	private final String PERMISSION_CCENTER_ADMIN = "ccenter_admin";
	private final String PERMISSION_CCENTER_SUPERVISOR = "ccenter_supervisor";
	
	private final List<String> PERMISSIONS = new ArrayList<String>();

	public LoginController() {
		System.out.println("Ingreso a LoginController");
		PERMISSIONS.add(PERMISSION_CCENTER_ADMIN);
		PERMISSIONS.add(PERMISSION_CCENTER_AGENT);
		PERMISSIONS.add(PERMISSION_CCENTER_SUPERVISOR);
	}

	public String doLogin() {

		//System.out.println("ingreso a doLogin");

		try {
			
			
			// INICIALIZA BEAN
			UserInterface userService = (UserInterface) new InitialContext(
					Util.getInitProperties())
					.lookup("java:global/SecurityEAR/SecurityEJB/UserBean"
							+ "!com.returnsoft.security.service.UserInterface");
			// BUSCA USUARIO Y CLAVE
			UserDto user = userService.doLogin(username, password, PERMISSIONS);
			System.out.println("id de usuario:"+user.getId());

			
			List<PermissionDto> permissions = user.getPermissions();
			SessionBean session = new SessionBean();
			for (PermissionDto permissionDto : permissions) {
				//System.out.println(permissionDto.getCode());
				
				if (permissionDto.getCode().equals(PERMISSION_CCENTER_ADMIN)) {
					session.setAdminId(user.getId());
					//System.out.println("Ingreso a ccenter admin");
				} else if (permissionDto.getCode().equals(
						PERMISSION_CCENTER_SUPERVISOR)) {
					SupervisorInterface supervisorService = (SupervisorInterface) new InitialContext(
							Util.getInitProperties())
							.lookup("java:global/CCenterEAR/CCenterEJB/SupervisorBean"
									+ "!com.returnsoft.softphone.service.SupervisorInterface");
					SupervisorDto supervisorDto = supervisorService.findSupervisor(user.getId());
					if (supervisorDto!=null && supervisorDto.getId()>0) {
						session.setSupervisorId(supervisorDto.getId());	
					}else{
						FacesMessage msg = new FacesMessage("No se encontro supervisor", "No se encontro supervisor");
						msg.setSeverity(FacesMessage.SEVERITY_ERROR);
						FacesContext.getCurrentInstance().addMessage(null, msg);
						return null;
					}
					
					
				} else if (permissionDto.getCode().equals(
						PERMISSION_CCENTER_AGENT)){
					AgentInterface agentService = (AgentInterface) new InitialContext(
							Util.getInitProperties())
							.lookup("java:global/CCenterEAR/CCenterEJB/AgentBean"
									+ "!com.returnsoft.softphone.service.AgentInterface");
					AgentDto agent = agentService.findAgent(user.getId());
					
					if (agent!=null && agent.getId()>0) {
						session.setAgentId(agent.getId());	
					}else{
						FacesMessage msg = new FacesMessage("No se encontro agente", "No se encontro agente");
						msg.setSeverity(FacesMessage.SEVERITY_ERROR);
						FacesContext.getCurrentInstance().addMessage(null, msg);
						return null;
					}
				}
			}

			session.setName(user.getPerson().getFirstname() + " "
					+ user.getPerson().getLastname());
			session.setUsername(username);

			// SE GUARDA LA SESION
			FacesContext.getCurrentInstance().getExternalContext()
					.getSessionMap().put("sessionBean", session);
			


			if (session.getAgentId()!=null && session.getAgentId()>0) {
				return "agent_panel?faces-redirect=true";
			} else {
				return "ccenter?faces-redirect=true";
			}
			

		}catch (Exception e) {
			
			if (!(e instanceof CCenterExcepcion) && !(e instanceof SecurityExcepcion)) {
				e.printStackTrace();	
			}
			FacesMessage msg = new FacesMessage(e.getMessage(), e.getMessage());
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			FacesContext.getCurrentInstance().addMessage(null, msg);
			return null;
		}

	}

	public String doLogout() {
		System.out.println("ingreso a doLogout");
		try {
			// OBTIENE LA SESSION
			SessionBean session = (SessionBean) FacesContext
					.getCurrentInstance().getExternalContext().getSessionMap()
					.get("sessionBean");

			Integer agentId = session.getAgentId();
			String sessionTypeSelected = session.getSessionTypeSelected();

			if (agentId != null && agentId > 0) {
				
				if (sessionTypeSelected !=null && !sessionTypeSelected.equals("")) {
					HttpServletRequest request = (HttpServletRequest) FacesContext
							.getCurrentInstance().getExternalContext().getRequest();
					String host = request.getRemoteAddr();

					 AgentInterface agentService = (AgentInterface) new InitialContext(
							Util.getInitProperties())
							.lookup("java:global/CCenterEAR/CCenterEJB/AgentBean"
									+ "!com.returnsoft.softphone.service.AgentInterface");
					 
					agentService.changeState(agentId, host, "logout");
				}

			}

			FacesContext.getCurrentInstance().getExternalContext()
					.invalidateSession();
			return "login?faces-redirect=true";

		} catch (Exception e) {
			if (!(e instanceof CCenterExcepcion) && !(e instanceof SecurityExcepcion)) {
				e.printStackTrace();	
			}
			FacesMessage msg = new FacesMessage(e.getMessage(), null);
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			FacesContext.getCurrentInstance().addMessage(null, msg);
			return null;
		}

	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
